/**
 * 数据迁移服务
 * 负责将localStorage中的智能体数据迁移到服务器端
 */

import type { Agent, CreateAgentInput } from '../types/agent'
import { addAgent as addAgentService, deleteAgent as deleteAgentService } from './dataService'

/** localStorage中智能体数据的键名 */
const AGENTS_STORAGE_KEY = 'agents'

/** 迁移状态标记键名 */
const MIGRATION_STATUS_KEY = 'migration_completed'

/**
 * 迁移结果接口
 */
export interface MigrationResult {
  /** 迁移是否成功 */
  success: boolean
  /** 迁移的智能体数量 */
  migratedCount: number
  /** 失败的智能体数量 */
  failedCount: number
  /** 错误信息列表 */
  errors: string[]
  /** 详细信息 */
  message: string
  /** 已成功迁移的智能体ID列表（用于回滚） */
  migratedAgentIds?: string[]
}

/**
 * 回滚结果接口
 */
export interface RollbackResult {
  /** 回滚是否成功 */
  success: boolean
  /** 回滚的智能体数量 */
  rolledBackCount: number
  /** 回滚失败的数量 */
  failedCount: number
  /** 错误信息列表 */
  errors: string[]
  /** 详细信息 */
  message: string
}

/**
 * 迁移进度回调函数类型
 */
export type MigrationProgressCallback = (current: number, total: number, agentName: string) => void

/**
 * 检查localStorage中是否存在智能体数据
 * @returns 返回是否存在数据和数据数量
 */
export function checkLocalStorageData(): { hasData: boolean; count: number } {
  try {
    const data = localStorage.getItem(AGENTS_STORAGE_KEY)
    if (!data) {
      return { hasData: false, count: 0 }
    }

    const agents = JSON.parse(data)
    if (!Array.isArray(agents)) {
      return { hasData: false, count: 0 }
    }

    return { hasData: agents.length > 0, count: agents.length }
  } catch (error) {
    console.error('检查localStorage数据失败:', error)
    return { hasData: false, count: 0 }
  }
}

/**
 * 检查是否已经完成过迁移
 * @returns 返回是否已完成迁移
 */
export function isMigrationCompleted(): boolean {
  try {
    const status = localStorage.getItem(MIGRATION_STATUS_KEY)
    return status === 'true'
  } catch (error) {
    console.error('检查迁移状态失败:', error)
    return false
  }
}

/**
 * 标记迁移已完成
 */
export function markMigrationCompleted(): void {
  try {
    localStorage.setItem(MIGRATION_STATUS_KEY, 'true')
  } catch (error) {
    console.error('标记迁移状态失败:', error)
  }
}

/**
 * 从localStorage获取智能体数据
 * @returns 返回智能体数据数组
 */
function getLocalStorageAgents(): Agent[] {
  try {
    const data = localStorage.getItem(AGENTS_STORAGE_KEY)
    if (!data) {
      return []
    }

    const agents = JSON.parse(data)
    if (!Array.isArray(agents)) {
      return []
    }

    return agents
  } catch (error) {
    console.error('读取localStorage数据失败:', error)
    return []
  }
}

/**
 * 将Agent数据转换为CreateAgentInput格式
 * @param agent 智能体数据
 * @returns 返回创建智能体的输入数据
 */
function convertAgentToInput(agent: Agent): CreateAgentInput {
  return {
    name: agent.name,
    description: agent.description,
    author: agent.author,
    version: agent.version,
    category: agent.category,
    tags: agent.tags,
    shareUrl: agent.shareUrl
  }
}

/**
 * 执行数据迁移（带错误处理和回滚机制）
 * @param progressCallback 进度回调函数
 * @returns 返回迁移结果
 */
export async function migrateData(progressCallback?: MigrationProgressCallback): Promise<MigrationResult> {
  const result: MigrationResult = {
    success: false,
    migratedCount: 0,
    failedCount: 0,
    errors: [],
    message: '',
    migratedAgentIds: []
  }

  // 备份原始数据，用于回滚
  let originalData: string | null = null
  
  try {
    // 检查是否已经迁移过
    if (isMigrationCompleted()) {
      result.success = true
      result.message = '数据已经迁移过，无需重复迁移'
      return result
    }

    // 备份原始localStorage数据
    originalData = localStorage.getItem(AGENTS_STORAGE_KEY)
    
    // 获取localStorage中的数据
    const localAgents = getLocalStorageAgents()
    if (localAgents.length === 0) {
      result.success = true
      result.message = '没有需要迁移的数据'
      return result
    }

    console.log(`开始迁移 ${localAgents.length} 个智能体数据`)

    // 逐个迁移智能体数据
    for (let i = 0; i < localAgents.length; i++) {
      const agent = localAgents[i]
      
      try {
        // 调用进度回调
        if (progressCallback) {
          progressCallback(i + 1, localAgents.length, agent.name)
        }

        // 转换数据格式并添加到服务器
        const input = convertAgentToInput(agent)
        const addResult = await addAgentService(input)

        if (addResult.success && addResult.data) {
          result.migratedCount++
          result.migratedAgentIds!.push(addResult.data.id)
          console.log(`成功迁移智能体: ${agent.name}`)
        } else {
          result.failedCount++
          const errorMsg = `迁移智能体 "${agent.name}" 失败: ${addResult.error || '未知错误'}`
          result.errors.push(errorMsg)
          console.error(errorMsg)
        }
      } catch (error) {
        result.failedCount++
        const errorMessage = error instanceof Error ? error.message : '未知错误'
        const errorMsg = `迁移智能体 "${agent.name}" 失败: ${errorMessage}`
        result.errors.push(errorMsg)
        console.error(errorMsg, error)
      }
    }

    // 判断迁移是否成功
    const migrationSuccess = result.failedCount === 0
    
    if (migrationSuccess) {
      result.success = true
      result.message = `成功迁移 ${result.migratedCount} 个智能体`
      // 标记迁移完成
      markMigrationCompleted()
      console.log('数据迁移完成')
    } else {
      // 部分失败的情况
      result.success = false
      result.message = `迁移完成，成功 ${result.migratedCount} 个，失败 ${result.failedCount} 个`
      console.warn('数据迁移部分失败:', result.message)
      
      // 如果失败率超过50%，考虑回滚已迁移的数据
      const failureRate = result.failedCount / (result.migratedCount + result.failedCount)
      if (failureRate > 0.5 && result.migratedAgentIds!.length > 0) {
        console.warn('失败率过高，开始回滚已迁移的数据')
        const rollbackResult = await rollbackMigratedData(result.migratedAgentIds!)
        if (rollbackResult.success) {
          result.message += '，已回滚成功迁移的数据'
        } else {
          result.message += '，回滚失败，请手动清理重复数据'
          result.errors.push(...rollbackResult.errors)
        }
      }
    }

  } catch (error) {
    result.success = false
    const errorMessage = error instanceof Error ? error.message : '迁移过程中发生未知错误'
    result.message = errorMessage
    result.errors.push(errorMessage)
    console.error('迁移过程发生严重错误:', error)
    
    // 发生严重错误时，尝试恢复原始数据
    if (originalData && result.migratedAgentIds!.length > 0) {
      console.log('尝试恢复原始localStorage数据')
      try {
        localStorage.setItem(AGENTS_STORAGE_KEY, originalData)
        // 回滚已迁移到服务器的数据
        await rollbackMigratedData(result.migratedAgentIds!)
      } catch (restoreError) {
        console.error('恢复原始数据失败:', restoreError)
        result.errors.push('恢复原始数据失败，请手动处理')
      }
    }
  }

  return result
}

/**
 * 清理localStorage中的智能体数据
 * 注意：只有在迁移成功后才应该调用此函数
 */
export function cleanupLocalStorageData(): void {
  try {
    localStorage.removeItem(AGENTS_STORAGE_KEY)
    console.log('已清理localStorage中的智能体数据')
  } catch (error) {
    console.error('清理localStorage数据失败:', error)
  }
}

/**
 * 回滚已迁移到服务器的数据
 * @param agentIds 需要回滚的智能体ID列表
 * @returns 返回回滚结果
 */
export async function rollbackMigratedData(agentIds: string[]): Promise<RollbackResult> {
  const result: RollbackResult = {
    success: false,
    rolledBackCount: 0,
    failedCount: 0,
    errors: [],
    message: ''
  }

  if (agentIds.length === 0) {
    result.success = true
    result.message = '没有需要回滚的数据'
    return result
  }

  console.log(`开始回滚 ${agentIds.length} 个智能体数据`)

  // 逐个删除已迁移的智能体
  for (const agentId of agentIds) {
    try {
      const deleteResult = await deleteAgentService(agentId)
      
      if (deleteResult.success) {
        result.rolledBackCount++
        console.log(`成功回滚智能体: ${agentId}`)
      } else {
        result.failedCount++
        const errorMsg = `回滚智能体 ${agentId} 失败: ${deleteResult.error || '未知错误'}`
        result.errors.push(errorMsg)
        console.error(errorMsg)
      }
    } catch (error) {
      result.failedCount++
      const errorMessage = error instanceof Error ? error.message : '未知错误'
      const errorMsg = `回滚智能体 ${agentId} 失败: ${errorMessage}`
      result.errors.push(errorMsg)
      console.error(errorMsg, error)
    }
  }

  // 判断回滚是否成功
  result.success = result.failedCount === 0
  
  if (result.success) {
    result.message = `成功回滚 ${result.rolledBackCount} 个智能体`
    console.log('数据回滚完成')
  } else {
    result.message = `回滚完成，成功 ${result.rolledBackCount} 个，失败 ${result.failedCount} 个`
    console.warn('数据回滚部分失败:', result.message)
  }

  return result
}

/**
 * 验证迁移后的数据完整性
 * @param originalAgents 原始智能体数据
 * @param migratedAgentIds 已迁移的智能体ID列表
 * @returns 返回验证结果
 */
export async function validateMigrationData(
  originalAgents: Agent[], 
  migratedAgentIds: string[]
): Promise<{ isValid: boolean; errors: string[] }> {
  const errors: string[] = []
  
  try {
    // 检查迁移数量是否匹配
    if (originalAgents.length !== migratedAgentIds.length) {
      errors.push(`数据数量不匹配: 原始 ${originalAgents.length} 个，迁移 ${migratedAgentIds.length} 个`)
    }
    
    // 这里可以添加更多的数据完整性检查
    // 比如检查服务器上的数据是否与原始数据一致
    
    return {
      isValid: errors.length === 0,
      errors
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '验证过程发生未知错误'
    errors.push(errorMessage)
    console.error('数据验证失败:', error)
    
    return {
      isValid: false,
      errors
    }
  }
}

/**
 * 重置迁移状态（用于测试或重新迁移）
 */
export function resetMigrationStatus(): void {
  try {
    localStorage.removeItem(MIGRATION_STATUS_KEY)
    console.log('已重置迁移状态')
  } catch (error) {
    console.error('重置迁移状态失败:', error)
  }
}

/**
 * 创建数据备份
 * @returns 返回备份的数据字符串
 */
export function createDataBackup(): string | null {
  try {
    const data = localStorage.getItem(AGENTS_STORAGE_KEY)
    if (data) {
      const timestamp = new Date().toISOString()
      const backup = {
        timestamp,
        data: JSON.parse(data)
      }
      return JSON.stringify(backup)
    }
    return null
  } catch (error) {
    console.error('创建数据备份失败:', error)
    return null
  }
}

/**
 * 从备份恢复数据
 * @param backupData 备份数据字符串
 * @returns 返回是否恢复成功
 */
export function restoreFromBackup(backupData: string): boolean {
  try {
    const backup = JSON.parse(backupData)
    if (backup.data && Array.isArray(backup.data)) {
      localStorage.setItem(AGENTS_STORAGE_KEY, JSON.stringify(backup.data))
      console.log('数据恢复成功，备份时间:', backup.timestamp)
      return true
    }
    return false
  } catch (error) {
    console.error('从备份恢复数据失败:', error)
    return false
  }
}